package com.example.rabbit.demo.returnlistener;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @program: rabbit-demo
 * @description:
 * @author: zhaoliang
 * @create: 2019-12-30 13:38
 */
public class ProducerReturn {

    public static void main(String[] args) throws Exception {
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.200.128");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/zl");
        connectionFactory.setPassword("123456");
        connectionFactory.setUsername("zhaoliang");

        //2.通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();
        //3.通过connection创建一个channel
        Channel channel = connection.createChannel();

        //4.指定消息投递模式：消息的确认模式
        channel.confirmSelect();

        String exchangeName = "test_return_exchange";
        String routingKey = "return.save";
        String routingKeyError = "abc.save";
        //5.发送一条消息
        String msg = "Hello RabbitMQ Send return message";

        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int i, String s, String s1, String s2, AMQP.BasicProperties basicProperties, byte[] bytes)
                    throws IOException {
                System.out.println("---------handleReturn-------------");
                System.out.println("replyCode:"+i);
                System.out.println("replyText:"+s);
                System.out.println("exchange:"+s1);
                System.out.println("routingKey:"+s2);
                System.out.println("properties:"+basicProperties);
                System.out.println("body:"+new String(bytes));
            }
        });
        //成功演示
        // channel.basicPublish(exchangeName,routingKey,null,msg.getBytes());

        //失败演示
        channel.basicPublish(exchangeName,routingKeyError,true,null,msg.getBytes());

       /* channel.close();
        connection.close();*/

    }
}
